package io.renren.modules.pet.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.page.PageData;
import io.renren.common.utils.ConvertUtils;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.modules.pet.dao.PetSendDao;
import io.renren.modules.pet.enums.PetBreedEnum;
import io.renren.modules.pet.enums.PetStatusEnum;
import io.renren.modules.pet.service.PetCollectService;
import io.renren.modules.pet.service.PetLostCollectService;
import io.renren.modules.pet.vo.PetCollectVO;
import io.renren.modules.pet.vo.PetLostCollectVO;
import io.renren.modules.pet.vo.PetSendVO;
import io.renren.modules.pet.dto.PetSendDTO;
import io.renren.modules.pet.entity.PetSendEntity;
import io.renren.modules.pet.service.PetSendService;
import io.renren.modules.pet.vo.PetTypeChartPieVO;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.sys.entity.DictData;
import io.renren.modules.sys.entity.DictType;
import io.renren.modules.sys.service.SysDictTypeService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 宠物送养信息
 *
 * @author zwp zwp
 * @since 1.0.0 2025-03-07
 */
@Service
public class PetSendServiceImpl extends CrudServiceImpl<PetSendDao, PetSendEntity, PetSendVO> implements PetSendService {

    @Autowired
    private SysDictTypeService sysDictTypeService;

    @Autowired
    private PetCollectService petCollectService;

    @Override
    public QueryWrapper<PetSendEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        String petName = (String)params.get("petName");
        String petStatus = (String)params.get("petStatus");

        QueryWrapper<PetSendEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        wrapper.like(StringUtils.isNotBlank(petName), "pet_name", petName);
        wrapper.eq(StringUtils.isNotBlank(petStatus), "pet_status", petStatus);
        wrapper.orderByDesc("create_date");

        return wrapper;
    }

    @Override
    public void save(PetSendDTO petSendDTO) {
        PetSendEntity petSendEntity = ConvertUtils.sourceToTarget(petSendDTO, PetSendEntity.class);
        this.insert(petSendEntity);
    }

    @Override
    public void update(PetSendDTO petSendDTO) {
        PetSendEntity petSendEntity = ConvertUtils.sourceToTarget(petSendDTO, PetSendEntity.class);
        this.updateById(petSendEntity);
    }

    @Override
    public List<PetSendVO> listDetailByUser(Map<String, Object> params) {
        String petStatus = (String)params.get("petStatus");
        String status = (String)params.get("status");
        // 获取当前用户信息
        Long userId = SecurityUser.getUserId();
        // 获取领养条件
        Map<String, Object> map = new HashMap<>();
        map.put("dictType", "adoptionConditions");
        DictType dictType = sysDictTypeService.getAllByType(map);
        List<DictData> dictDataList = dictType.getDataList();
        QueryWrapper<PetSendEntity> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(petStatus)) {
            wrapper.eq("pet_status", Integer.valueOf(petStatus));
        }
        if (StringUtils.isNotBlank(status)) {
            wrapper.eq("status", Integer.valueOf(status));
        }
        wrapper.eq("creator", userId);
        List<PetSendEntity> entityList = this.baseDao.selectList(wrapper);
        List<PetSendVO> petSendVoList = ConvertUtils.sourceToTarget(entityList, PetSendVO.class);
        petSendVoList.forEach(petSendVo -> {
            // 首页图片
            petSendVo.setFirstImageUrl(petSendVo.getImageUrl().split(",")[0]);
            // 领养条件
            if (StringUtils.isNotBlank(petSendVo.getSendConditions())) {
                List<String> sendConditionNameList = new ArrayList<>();
                for (String sendConditionId : petSendVo.getSendConditions().split(",")) {
                    DictData sendCondition = dictDataList.stream().filter(dictData -> dictData.getDictDataId().compareTo(Long.valueOf(sendConditionId)) == 0).findFirst().orElse(null);
                    sendConditionNameList.add(sendCondition.getDictValue());
                }
                petSendVo.setSendConditionNameList(sendConditionNameList);
            }
        });
        return petSendVoList;
    }

    @Override
    public List<PetSendVO> homeListDetail(Map<String, Object> params) {
        String petBreed = (String)params.get("petBreed");
        // 获取领养条件
        Map<String, Object> map = new HashMap<>();
        map.put("dictType", "adoptionConditions");
        DictType dictType = sysDictTypeService.getAllByType(map);
        List<DictData> dictDataList = dictType.getDataList();
        QueryWrapper<PetSendEntity> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(petBreed)) {
            wrapper.eq("pet_breed", Integer.valueOf(petBreed));
        }
        wrapper.eq("pet_status", 0);
        wrapper.eq("status", 1);
        List<PetSendEntity> entityList = this.baseDao.selectList(wrapper);
        List<PetSendVO> petSendVoList = ConvertUtils.sourceToTarget(entityList, PetSendVO.class);
        petSendVoList.forEach(petSendVo -> {
            // 首页图片
            petSendVo.setFirstImageUrl(petSendVo.getImageUrl().split(",")[0]);
            // 领养条件
            if (StringUtils.isNotBlank(petSendVo.getSendConditions())) {
                List<String> sendConditionNameList = new ArrayList<>();
                for (String sendConditionId : petSendVo.getSendConditions().split(",")) {
                    DictData sendCondition = dictDataList.stream().filter(dictData -> dictData.getDictDataId().compareTo(Long.valueOf(sendConditionId)) == 0).findFirst().orElse(null);
                    sendConditionNameList.add(sendCondition.getDictValue());
                }
                petSendVo.setSendConditionNameList(sendConditionNameList);
            }
        });
        return petSendVoList;
    }

    @Override
    public PetSendVO getInfoById(Long id) {
        PetSendEntity petSendEntity = this.selectById(id);
        PetSendVO petSendVo = ConvertUtils.sourceToTarget(petSendEntity, PetSendVO.class);
        // 获取领养条件
        Map<String, Object> map = new HashMap<>();
        map.put("dictType", "adoptionConditions");
        DictType dictType = sysDictTypeService.getAllByType(map);
        List<DictData> dictDataList = dictType.getDataList();
        if (petSendVo != null) {
            // 首页图片
            petSendVo.setFirstImageUrl(petSendVo.getImageUrl().split(",")[0]);
            // 照片集合
            petSendVo.setImageUrlList(Arrays.asList(petSendVo.getImageUrl().split(",")));
            // 领养条件
            if (StringUtils.isNotBlank(petSendVo.getSendConditions())) {
                List<String> sendConditionNameList = new ArrayList<>();
                for (String sendConditionId : petSendVo.getSendConditions().split(",")) {
                    DictData sendCondition = dictDataList.stream().filter(dictData -> dictData.getDictDataId().compareTo(Long.valueOf(sendConditionId)) == 0).findFirst().orElse(null);
                    sendConditionNameList.add(sendCondition.getDictValue());
                }
                petSendVo.setSendConditionNameList(sendConditionNameList);
            }
            // 收藏数量
            List<PetCollectVO> petCollectVoList = petCollectService.getByPetId(petSendVo.getId());
            petSendVo.setPetCollectNum(petCollectVoList.size());
            // 是否已收藏
            // 获取当前用户信息
            Long userId = SecurityUser.getUserId();
            PetCollectVO petCollectVo = petCollectService.getByUserPetId(userId, petSendVo.getId());
            if (petCollectVo != null) {
                petSendVo.setIsPetCollect(1);
            } else {
                petSendVo.setIsPetCollect(0);
            }
        }
        return petSendVo;
    }

    @Override
    public List<PetSendVO> getListByIdList(List<Long> IdList) {
        List<PetSendEntity> entityList = this.baseDao.selectBatchIds(IdList);
        return ConvertUtils.sourceToTarget(entityList, PetSendVO.class);
    }

    @Override
    public List<PetSendVO> getPetCollectByUser(Map<String, Object> params) {
        // 当前用户
        Long userId = SecurityUser.getUserId();
        String petBreed = (String)params.get("petBreed");
        // 获取领养条件
        Map<String, Object> map = new HashMap<>();
        map.put("dictType", "adoptionConditions");
        DictType dictType = sysDictTypeService.getAllByType(map);
        List<DictData> dictDataList = dictType.getDataList();
        // 获取当前用户的宠物收藏表
        List<PetCollectVO> petCollectVoList = petCollectService.getByUserId(userId);
        if (CollectionUtils.isEmpty(petCollectVoList)) {
            return Collections.EMPTY_LIST;
        }
        QueryWrapper<PetSendEntity> wrapper = new QueryWrapper<>();
        wrapper.in("id", petCollectVoList.stream().map(e -> e.getPetSendId()).distinct().collect(Collectors.toList()));
        if (StringUtils.isNotBlank(petBreed)) {
            wrapper.eq("pet_breed", Integer.valueOf(petBreed));
        }
        wrapper.eq("pet_status", 0);
        wrapper.eq("status", 1);
        List<PetSendEntity> entityList = this.baseDao.selectList(wrapper);
        List<PetSendVO> petSendVoList = ConvertUtils.sourceToTarget(entityList, PetSendVO.class);
        petSendVoList.forEach(petSendVo -> {
            // 首页图片
            petSendVo.setFirstImageUrl(petSendVo.getImageUrl().split(",")[0]);
            // 领养条件
            if (StringUtils.isNotBlank(petSendVo.getSendConditions())) {
                List<String> sendConditionNameList = new ArrayList<>();
                for (String sendConditionId : petSendVo.getSendConditions().split(",")) {
                    DictData sendCondition = dictDataList.stream().filter(dictData -> dictData.getDictDataId().compareTo(Long.valueOf(sendConditionId)) == 0).findFirst().orElse(null);
                    sendConditionNameList.add(sendCondition.getDictValue());
                }
                petSendVo.setSendConditionNameList(sendConditionNameList);
            }
        });
        return petSendVoList;
    }

    @Override
    public PageData<PetSendVO> petSendPage(Map<String, Object> params) {
        // 获取领养条件
        Map<String, Object> map = new HashMap<>();
        map.put("dictType", "adoptionConditions");
        DictType dictType = sysDictTypeService.getAllByType(map);
        List<DictData> dictDataList = dictType.getDataList();

        PageData<PetSendVO> page = this.page(params);
        page.getList().forEach(petSendVo -> {
            // 照片集合
            petSendVo.setImageUrlList(Arrays.asList(petSendVo.getImageUrl().split(",")));
            petSendVo.setImageUrlSize(petSendVo.getImageUrlList().size());
            // 领养条件
            if (StringUtils.isNotBlank(petSendVo.getSendConditions())) {
                List<String> sendConditionNameList = new ArrayList<>();
                for (String sendConditionId : petSendVo.getSendConditions().split(",")) {
                    DictData sendCondition = dictDataList.stream().filter(dictData -> dictData.getDictDataId().compareTo(Long.valueOf(sendConditionId)) == 0).findFirst().orElse(null);
                    sendConditionNameList.add(sendCondition.getDictValue());
                }
                petSendVo.setSendConditionNameList(sendConditionNameList);
            }
        });
        return page;
    }

    @Override
    public List<PetTypeChartPieVO> getPetTypeChartPie(Map<String, Object> params) {
        QueryWrapper<PetSendEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1);
        List<PetSendEntity> entityList = this.baseDao.selectList(wrapper);
        if (CollectionUtils.isEmpty(entityList)) {
            return Collections.EMPTY_LIST;
        }
        List<PetTypeChartPieVO> list = new ArrayList<>();
        Map<Integer, List<PetSendEntity>> collect = entityList.stream().collect(Collectors.groupingBy(PetSendEntity::getPetBreed));
        collect.keySet().forEach(key -> {
            PetTypeChartPieVO petTypeChartPieVo = new PetTypeChartPieVO();
            petTypeChartPieVo.setName(PetBreedEnum.getChnByIndex(key));
            petTypeChartPieVo.setValue(collect.get(key).size());
            list.add(petTypeChartPieVo);
        });
        return list;
    }

    @Override
    public List<PetTypeChartPieVO> getPetStatusChartPie(Map<String, Object> params) {
        QueryWrapper<PetSendEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1);
        List<PetSendEntity> entityList = this.baseDao.selectList(wrapper);
        if (CollectionUtils.isEmpty(entityList)) {
            return Collections.EMPTY_LIST;
        }
        List<PetTypeChartPieVO> list = new ArrayList<>();
        Map<Integer, List<PetSendEntity>> collect = entityList.stream().collect(Collectors.groupingBy(PetSendEntity::getPetStatus));
        collect.keySet().forEach(key -> {
            PetTypeChartPieVO petTypeChartPieVo = new PetTypeChartPieVO();
            petTypeChartPieVo.setName(PetStatusEnum.getChnByIndex(key));
            petTypeChartPieVo.setValue(collect.get(key).size());
            list.add(petTypeChartPieVo);
        });
        return list;
    }

}